/**
 * PageMarket
 * FlowView.java
 * com.android.pagemarket.ui.widget
 * 
 */
package com.android.pagemarket.ui.widget;

import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Adapter;
import android.widget.LinearLayout;

import com.android.pagemarket.R;
import com.android.pagemarket.util.CycledThread;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-10-31
 * @see : 滑动广告控件
 * @Copyright : copyrights reserved by personal 2007-2012
 **********************************************************/
public class FlowView extends LinearLayout
{
    private ViewFlow viewFlow;
    private boolean autoSlide;
    private CycledThread mSlidAdvThread;
    
    public FlowView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        View row = inflate(getContext(), R.layout.view_flow_adv, null);
        addView(row,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        viewFlow = (ViewFlow) findViewById(R.id.viewflow);
        CircleFlowIndicator indic = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
        viewFlow.setFlowIndicator(indic);
    }
    
    public void setAdpter(Adapter adapter)
    {
        viewFlow.setAdapter(adapter);
    }
    
    public void setAutoSlide(boolean auto)
    {
        autoSlide = auto;
    }
        
    @Override
    protected void onWindowVisibilityChanged(int visibility)
    {
        super.onWindowVisibilityChanged(visibility);
        if(autoSlide)
        {
            if(visibility == View.VISIBLE)
            {
                startAutoSlidAdv();
            }else
            if(visibility == View.GONE)
            {
                stopAutoSlidAdv();
            }
        }
    }
    
    private void startAutoSlidAdv()
    {
        if(mSlidAdvThread == null)
        {
            mSlidAdvThread = new CycledThread(new Runnable()
            {
                @Override
                public void run()
                {
                    post(new Runnable()
                    {
                        public void run()
                        {
                            int size = viewFlow.getViewsCount();
                            if(size > 0)
                            {
                                viewFlow.snapToNextScreen();
                            }
                        }
                    });
                }
            },4000);
            mSlidAdvThread.start();
        }
    }
    
    private void stopAutoSlidAdv()
    {
        if(mSlidAdvThread != null && mSlidAdvThread.isAlive())
        {
            mSlidAdvThread._stop();
            mSlidAdvThread = null;
        }
    }
    
}
